<script lang="ts" setup>
import { computed, type Ref, ref, useTemplateRef, watch } from 'vue'
import { useDownloadImage } from '@/hooks/useDownloadImage'
import OtherMessage from "@/components/OtherMessage.vue";
import SystemMessage from "@/components/SystemMessage.vue";
import SelfMessage from "@/components/SelfMessage.vue";
import SelfTransferAccounts from "@/components/SelfTransferAccounts.vue";
import { chatVersionsList } from "@/data/chatList.ts";
import OtherReceive from "@/components/OtherReceive.vue";
import { useRandomTime } from "@/hooks/useRandomTime";
import { ElNotification } from 'element-plus';
import SelfWord from "@/components/SelfWord.vue";
import OtherWord from "@/components/OtherWord.vue";
import axios from 'axios'

// 昵称
const name: Ref<string> = ref('李贞美')
// 当前张数
const currentNumber: Ref<number> = ref(0)
// 自己头像地址
const selfAvatar: Ref<string> = ref('')
// 对方头像地址
const otherAvatar: Ref<string> = ref('')
// 选择版本
const versions: Ref<number> = ref<number>(0)
// 随机金额
const randomMoney: Ref<number | string> = ref(0)
// 随机金额起始范围
const minMoney: Ref<number> = ref(100)
// 随机金额结束范围
const maxMoney: Ref<number> = ref(500)
// 是否在执行自动保存
const isAutoSaving = ref<boolean>(false)
// 自动保存数量
const autoSaveNumber = ref<number>(203)
// 是否需要停止自动保存
const needStopAutoSave = ref<boolean>(false)
// 随机时间起始范围
const startTime: Ref<string> = ref('09:15')
// 随机时间结束范围
const endTime: Ref<string> = ref('22:30')
// 获取随机时间
const randomTime: Ref<string> = ref('')
// 处理后的数据
const processedChat = ref<Array<any>>([]);
// 控制随机未读消息开关
const controlUseUnreadCount: Ref<boolean> = ref(true)
// 随机未读消息数量
const unreadCount: Ref<number> = ref(1)
// 获取随机地区
const randomArea: Ref<string> = ref('四川成都')
// 内容ref
const content = useTemplateRef('content')
const chatBox: Ref<HTMLElement | null> = ref(null)

// 保存为图片
const { saveAsImage } = useDownloadImage()
const save = async () => {
  await saveAsImage(chatBox, currentNumber.value)
}

// 获取随机昵称
const getRandomName = async (needReturn = false) => {
  try {
    const response = await fetch('http://localhost:8080/api/getRandomName');
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    // 解析为文本
    const text = await response.text();
    if (!needReturn) {
      name.value = text.trim();
    }
    // 直接使用返回的文本作为昵称
    return text.trim();
  } catch (error) {
    console.error('Failed to fetch random name:', error);
    ElNotification({
      title: '失败',
      message: '获取随机昵称失败',
      type: 'error',
    })
  }
};

// 重命名壁纸目录文件
const renameWallpaper = async (): Promise<void> => {
  try {
    const response = await fetch('http://localhost:8080/api/formatImageNames')
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    // 弹窗提示
    ElNotification({
      title: '成功',
      message: '壁纸目录文件重命名成功',
      type: 'success',
    })
  } catch (error) {
    console.error('Failed to rename wallpaper directory:', error);
    ElNotification({
      title: '失败',
      message: '壁纸目录文件重命名失败',
      type: 'error',
    })
  }
}

// 添加壁纸路径
const addImagePath = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/saveImagePath', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify([])
    })
    ElNotification({
      title: '成功',
      message: '壁纸路径添加成功',
      type: 'success',
    })
  } catch (error) {
    console.error('Failed to add image path:', error);
    ElNotification({
      title: '失败',
      message: '添加壁纸路径失败',
      type: 'error',
    })
  }
}

// 聊天记录版本切换
const versionChange = async () => {
  // 更新金额范围并重新生成随机金额
  updateMoneyRange();
  getRandomMoney();
}

// 更新金额范围
const updateMoneyRange = () => {
  const currentVersion = chatVersionsList[versions.value];
  if (currentVersion?.moneyRange) {
    minMoney.value = currentVersion.moneyRange.min;
    maxMoney.value = currentVersion.moneyRange.max;
  }
}

// 获取随机头像 1 ~ 746
const getRandomAvatar = () => {
  selfAvatar.value = `../public/images/avatar/avatar-${Math.floor(Math.random() * 671 + 1)}.jpg`
  otherAvatar.value = `../public/images/avatar/avatar-${Math.floor(Math.random() * 671 + 1)}.jpg`
}

// 获取随机金额 100 ~ 500
const getRandomMoney = () => {
  randomMoney.value = Math.floor(Math.random() * (+maxMoney.value - (+minMoney.value) + 1) + (+minMoney.value))
}

// 随机金额 -w
const formatMoney = computed(() => {
  const money = String(randomMoney.value)
  // 如果金额小于100，补0到3位
  const paddedMoney = money.padStart(3, '0')
  // 在第一位插入小数点
  let result = paddedMoney.slice(0, 1) + '.' + paddedMoney.slice(1)
  // 如果末尾是0则删除
  while (result.endsWith('0')) {
    result = result.slice(0, -1)
  }
  return result
})

const { getContinuousTime } = useRandomTime()

// 获取随机不连续时间
// randomTime.value = getRandomTime(startTime.value, endTime.value) || ''


// 获取随机分期数
const getRandomStages = () => {
  if (+randomMoney.value < 120) {
    return 12
  } else {
    return Math.floor(Math.random() * 3 + 1) * 12
  }
}

// 获取随机未读消息数量 1 ~ 98
const getRandomUnreadCount = () => {
  unreadCount.value = Math.floor(Math.random() * 10 + 1)
}

/**
 * 返回随机中国省份+城市组合
 */
function getRandomRegion(): void {
  // 省份和城市数据（简化版，实际可扩展）
  const regions: Record<string, string[]> = {
    "河北": ["石家庄", "唐山", "秦皇岛", "邯郸", "邢台", "保定", "张家口", "承德", "沧州", "廊坊", "衡水"],
    "山西": ["太原", "大同", "阳泉", "长治", "晋城", "朔州", "晋中", "运城", "忻州", "临汾", "吕梁"],
    "辽宁": ["沈阳", "大连", "鞍山", "抚顺", "本溪", "丹东", "锦州", "营口", "阜新", "辽阳", "盘锦", "铁岭", "朝阳", "葫芦岛"],
    "江苏": ["南京", "无锡", "徐州", "常州", "苏州", "南通", "连云港", "淮安", "盐城", "扬州", "镇江", "泰州", "宿迁"],
    "浙江": ["杭州", "宁波", "温州", "嘉兴", "湖州", "绍兴", "金华", "衢州", "舟山", "台州", "丽水"],
    "安徽": ["合肥", "芜湖", "蚌埠", "淮南", "马鞍山", "淮北", "铜陵", "安庆", "黄山", "滁州", "阜阳", "宿州", "巢湖", "六安", "亳州", "池州", "宣城"],
    "福建": ["福州", "厦门", "莆田", "三明", "泉州", "漳州", "南平", "龙岩", "宁德"],
    "江西": ["南昌", "景德镇", "萍乡", "九江", "新余", "鹰潭", "赣州", "吉安", "宜春", "抚州", "上饶"],
    "山东": ["济南", "青岛", "淄博", "枣庄", "东营", "烟台", "潍坊", "济宁", "泰安", "威海", "日照", "莱芜", "临沂", "德州", "聊城", "滨州", "菏泽"],
    "河南": ["郑州", "开封", "洛阳", "平顶山", "安阳", "鹤壁", "新乡", "焦作", "濮阳", "许昌", "漯河", "三门峡", "南阳", "商丘", "信阳", "周口", "驻马店", "济源"],
    "湖北": ["武汉", "黄石", "十堰", "宜昌", "襄樊", "鄂州", "荆门", "孝感", "荆州", "黄冈", "咸宁", "随州", "恩施", "仙桃", "潜江", "天门", "神农架"],
    "湖南": ["长沙", "株洲", "湘潭", "衡阳", "邵阳", "岳阳", "常德", "张家界", "益阳", "郴州", "永州", "怀化", "娄底", "湘西"],
    "广东": ["广州", "深圳", "珠海", "汕头", "韶关", "佛山", "江门", "湛江", "茂名", "肇庆", "惠州", "梅州", "汕尾", "河源", "阳江", "清远", "东莞", "中山", "潮州", "揭阳", "云浮"],
    "广西": ["南宁", "柳州", "桂林", "梧州", "北海", "防城港", "钦州", "贵港", "玉林", "百色", "贺州", "河池", "来宾", "崇左"],
    "海南": ["海口", "三亚", "三沙", "儋州", "五指山", "琼海", "文昌", "万宁", "东方", "定安", "屯昌", "澄迈", "临高", "白沙", "昌江", "乐东", "陵水", "保亭", "琼中"],
    "四川": ["成都", "自贡", "攀枝花", "泸州", "德阳", "绵阳", "广元", "遂宁", "内江", "乐山", "南充", "眉山", "宜宾", "广安", "达州", "雅安", "巴中", "资阳", "阿坝", "甘孜", "凉山"],
    "贵州": ["贵阳", "六盘水", "遵义", "安顺", "毕节", "铜仁", "黔西南", "黔东南", "黔南"],
    "云南": ["昆明", "曲靖", "玉溪", "保山", "昭通", "丽江", "普洱", "临沧", "楚雄", "红河", "文山", "西双版纳", "大理", "德宏", "怒江", "迪庆"],
    "西藏": ["拉萨", "昌都", "山南", "日喀则", "那曲", "阿里", "林芝"],
    "陕西": ["西安", "铜川", "宝鸡", "咸阳", "渭南", "延安", "汉中", "榆林", "安康", "商洛"],
    "甘肃": ["兰州", "嘉峪关", "金昌", "白银", "天水", "武威", "张掖", "平凉", "酒泉", "庆阳", "定西", "陇南", "临夏", "甘南"],
    "青海": ["西宁", "海东", "海北", "黄南", "海南", "果洛", "玉树", "海西"],
    "宁夏": ["银川", "石嘴山", "吴忠", "固原", "中卫"],
  };

  // 获取所有省份数组
  const provinces = Object.keys(regions);
  // 随机选择一个省份
  const randomProvince = provinces[Math.floor(Math.random() * provinces.length)];

  // 获取该省份对应的城市数组
  const cities = regions[randomProvince];
  // 随机选择一个城市
  const randomCity = cities[Math.floor(Math.random() * cities.length)];

  randomArea.value = `${randomProvince}${randomCity}`;
}

// 获取下一个壁纸
// 原始逻辑
// const getNextBg = (): void => {
//   if (content.value) {
//     (content.value as HTMLElement).style.backgroundImage = `url('../public/images/bg/${++currentNumber.value}.png')`
//   }
// }

// 新逻辑：从接口获取随机壁纸
const getNextBg = async (): Promise<void> => {
  try {
    const response = await axios.get('http://localhost:8080/api/getRandomImage');
    if (content.value) {
      ++currentNumber.value;
      (content.value as HTMLElement).style.backgroundImage = `url('${response.data}')`;
    }
  } catch (error) {
    console.error('获取随机壁纸失败:', error);
    ElNotification({
      title: '失败',
      message: '获取随机壁纸失败',
      type: 'error',
    });
  }
}

// 获取下一张壁纸 —— Pexels
// const getNextBgPexels = async (): Promise<void> => {
//   const response = await fetch(`https://api.pexels.com/v1/search?query=nature`, {
//     headers: {
//       Authorization: 'uZJgVXp9WMH6PcRjnxbt7ObG1cHOxTg8I8P6KUqC8rXQgGqAz9WJnEAu',
//     },
//   });
//   const data = await response.json();
//   console.log(data);
// }

// 下一张
const nextPage = async () => {
  await getNextBg();
  // await getNextBgPexels();
  // getRandomTime();
  randomTime.value = getContinuousTime(randomTime.value, startTime.value, endTime.value) || '';
  getRandomMoney();
  getRandomRegion();
  getRandomAvatar();
  await getRandomName();
  await processChatList();
  if (controlUseUnreadCount.value) getRandomUnreadCount();
}

// 定义支持的组件类型
type ComponentType = 'system' | 'other' | 'self' | 'selfRefresherAccounts' | 'otherReceive' | 'selfWord' | 'otherWord';

const componentMap: Record<ComponentType, any> = {
  system: SystemMessage,
  other: OtherMessage,
  self: SelfMessage,
  selfRefresherAccounts: SelfTransferAccounts,
  otherReceive: OtherReceive,
  selfWord: SelfWord,
  otherWord: OtherWord,
};

const getComponent = (type: ComponentType) => componentMap[type];

const propStrategies: Record<ComponentType, (item: any) => Promise<Record<string, any>>> = {
  system: async () => ({
    message: "以上是打招呼的内容"
  }),
  other: async (item: any) => ({
    src: otherAvatar.value,
    noWrap: item.noWrap,
    message: await getMessage(item),
  }),
  self: async (item: any) => ({
    src: selfAvatar.value,
    noWrap: item.noWrap,
    message: await getMessage(item),
  }),
  selfRefresherAccounts: async (item: any) => ({
    src: selfAvatar.value,
    isReceive: item.isReceive,
    message: await getMessage(item),
  }),
  otherReceive: async (item: any) => ({
    src: otherAvatar.value,
    message: await getMessage(item),
  }),
  selfWord: async (item: any) => ({
    src: selfAvatar.value,
    message: await getMessage(item),
  }),
  otherWord: async (item: any) => ({
    src: otherAvatar.value,
    message: await getMessage(item),
  })
};

const getProps = async (item: { type: ComponentType }) => {
  const strategy = propStrategies[item.type];
  return strategy ? await strategy(item) : {};
};

const getMessage = async (item: any) => {
  if (!item.message.includes('${')) {
    return item.message;
  }
  
  let message = item.message;
  
  // 处理金额变量
  if (message.includes('${money}')) {
    const moneyValue = (item.type === 'selfRefresherAccounts' || item.type === 'otherReceive')
      ? `${randomMoney.value}00.00`
      : `${randomMoney.value}00`;
    message = message.replace(/\${money}/g, moneyValue);
  }
  
  // 处理名称变量
  if (message.includes('${name}')) {
    message = message.replace(/\${name}/g, name.value);
  }
  
  // 处理自己名称变量
  if (message.includes('${selfName}')) {
    const _name = await getRandomName(true);
    message = message.replace(/\${selfName}/g, _name || '');
  }
  
  // 处理时间变量
  if (message.includes('${time}')) {
    message = message.replace(/\${time}/g, randomTime.value);
  }
  
  // 处理分期数变量
  if (message.includes('${stages}')) {
    message = message.replace(/\${stages}/g, getRandomStages());
  }
  
  // 处理金额-w变量
  if (message.includes('${money-w}')) {
    message = message.replace(/\${money-w}/g, formatMoney.value);
  }
  
  // 处理金额-w*1000变量
  if (message.includes('${money-w*1000}')) {
    message = message.replace(/\${money-w\*1000}/g, (+formatMoney.value * 1000).toString());
  }
  
  // 处理地区变量
  if (message.includes('${area}')) {
    message = message.replace(/\${area}/g, randomArea.value);
  }
  
  return message;
};

// 处理聊天内容
const processChatList = async () => {
  const currentVersion = chatVersionsList[versions.value];
  if (!currentVersion) return;

  processedChat.value = await Promise.all(
    currentVersion.messages.map(async (item) => ({
      type: item.type,
      props: await getProps(item)
    }))
  );
};

// 监听版本变化
watch(() => versions.value, async () => {
  updateMoneyRange();
  getRandomMoney();
  await processChatList();
}, { immediate: true });

// 是否禁用操作按钮
const disabledOperate = computed(() => {
  return isAutoSaving.value
})

// 自动下载保存
const autoDownload = async () => {
  isAutoSaving.value = true
  needStopAutoSave.value = false
  let versionCount = 0 // 版本计数器

  for (let i = 0; i < autoSaveNumber.value; i++) {
    if (needStopAutoSave.value) {
      break
    }
    // 设置当前版本号（0-12循环）
    versions.value = versionCount
    versionCount = (versionCount + 1) % chatVersionsList.length

    await nextPage()
    await save()
  }
  isAutoSaving.value = false
}

// 停止自动保存
const stopAutoSave = () => {
  needStopAutoSave.value = true
}
</script>

<template>
  <div class="layout">
    <!-- 操作 -->
    <div class="operate-box">
      <h3>操作区域</h3>
      <div class="operate">
        <el-form
          inline
          label-position="top"
          label-width="120px"
          size="large">
          <el-form-item label="当前张数">
            <el-input
              v-model="currentNumber"
              size="large"
              type="number"
              placeholder="请输入当前张数"
              style="width: 200px;">
              <template #suffix>张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="版本">
            <el-select style="width: 200px" @change="versionChange" placeholder="请选择版本"
              v-model="versions"
              size="large">
              <!-- <el-option label="养小猪进小猪仔" value="0"></el-option> -->
              <!--<el-option label="没买保险创人" value="0"></el-option>-->
              <!-- <el-option label="裁员没奶粉没学费" value="2"></el-option> -->
              <!--<el-option label="经理介绍添加" value="1"></el-option>-->
              <!-- <el-option label="拉货买车差一点" value="4"></el-option> -->
              <el-option label="下了吗" value="0"></el-option>
              <!-- <el-option label="摆摊被城管没收交赎金" value="6"></el-option> -->
              <el-option label="信息填错" value="1"></el-option>
              <el-option label="预付一年店铺租金" value="2"></el-option>
              <!-- <el-option label="申请签下来了" value="9"></el-option> -->
              <!-- <el-option label="出差垫付一个月生活费" value="10"></el-option> -->
              <el-option label="以为会被拒绝" value="3"></el-option>
              <el-option label="江湖救急" value="4"></el-option>
              <el-option label="修车" value="5"></el-option>
              <el-option label="失业" value="6"></el-option>
              <el-option label="打官司" value="7"></el-option>
              <el-option label="补房子" value="8"></el-option>
              <el-option label="奶茶店倒闭" value="9"></el-option>
              <el-option label="填了签了" value="10"></el-option>
              <!-- <el-option label="测试" value="19"></el-option> -->
              <el-option label="快手来的" value="11"></el-option>
              <el-option label="主页来的" value="12"></el-option>
              <el-option label="早产" value="13"></el-option>
              <el-option label="创业差一点" value="14"></el-option>
              <el-option label="离婚带娃" value="15"></el-option>
              <el-option label="看演唱会" value="16"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="随机金额起始范围">
            <el-input v-model="minMoney" size="large" type="number" placeholder="请输入随机金额起始范围"
              style="width: 200px;">
              <template #prefix>￥</template>
              <template #suffix>00.00</template>
            </el-input>
          </el-form-item>
          <el-form-item label="随机金额结束范围">
            <el-input v-model="maxMoney" size="large" type="number" placeholder="请输入随机金额结束范围"
              style="width: 200px;">
              <template #prefix>￥</template>
              <template #suffix>00.00</template>
            </el-input>
          </el-form-item>
          <el-form-item label="随机时间起始范围">
            <el-time-select v-model="startTime" :max-time="endTime" placeholder="随机时间起始范围"
              start="00:00"
              step="00:15" end="23:30" size="large" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="随机时间结束范围">
            <el-time-select v-model="endTime" :min-time="startTime" placeholder="随机时间结束范围"
              start="15:00"
              step="00:15" end="23:30" size="large" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="设置自动保存数量">
            <el-input v-model="autoSaveNumber" size="large" type="number" placeholder="请输入随机金额结束范围"
              style="width: 200px;" />
          </el-form-item>
          <el-form-item label="开启随机未读消息数量">
            <el-switch v-model="controlUseUnreadCount" size="large" active-text="开启"
              inactive-text="关闭" />
          </el-form-item>
        </el-form>
        <div style="margin-top: 29px;">
          <el-button type="primary" @click="autoDownload" size="large" v-if="!isAutoSaving">自动保存
          </el-button>
          <el-button type="danger" @click="stopAutoSave" size="large" v-else>停止自动保存</el-button>
          <el-button type="primary" @click="nextPage" size="large" :disabled="disabledOperate">下一张
          </el-button>
          <el-button type="primary" @click="save" size="large" :disabled="disabledOperate">保存为图片
          </el-button>
          <el-button type="primary" @click="renameWallpaper" size="large">重命名壁纸</el-button>
          <el-button type="primary" @click="addImagePath" size="large">添加壁纸路径</el-button>
        </div>
      </div>
    </div>
    <!-- 预览 -->
    <div class="preview">
      <h3>效果预览</h3>
      <div class="view-box flex justify-center items-center">
        <div ref="chatBox" class="chat-box overflow-hidden relative">
          <!-- 聊天页面底图 -->
          <img src="./images/bg.png" alt="">
          <!-- 时间 -->
          <div class="time absolute">
            <span class="hour">{{ randomTime.split(':')[0] || '22' }}</span>
            <span class="time-split-char">:</span>
            <span class="minute">{{ randomTime.split(':')[1] || '49' }}</span>
          </div>
          <!-- 未读消息数量 -->
          <div v-if="controlUseUnreadCount"
            class="unread-count absolute flex justify-center items-center">
            {{ unreadCount }}
          </div>
          <!-- 昵称 -->
          <div class="nickname-box absolute flex justify-center items-center w-full">
            <div class="nickname">{{ name }}</div>
          </div>
          <!-- 聊天内容 -->
          <div ref="content" class="content-box w-full absolute">
            <component v-for="(item, index) in processedChat" :key="index"
              :is="getComponent(item.type)"
              v-bind="item.props" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.layout {
  width: 100%;
  display: flex;
  box-sizing: border-box;
  height: 100vh;
  color: #333;
  user-select: none;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;

  .operate-box {
    width: 50%;
    padding: 20px;
    border-right: 1px dashed #999;
    background-color: #f8f8f8;

    h3 {
      font-weight: normal;
      margin-bottom: 20px;
    }
  }

  .preview {
    width: 50%;
    padding: 20px;
    background-color: #ffffff;

    h3 {
      font-weight: normal;
    }

    .view-box {
      width: 100%;
      display: flex;
      height: calc(100% - 20px);

      .chat-box {
        width: 400px;
        height: fit-content;
        background-color: #b78888;

        img {
          z-index: -1;
        }

        .time {
          top: 18px;
          left: 50px;
          color: #000;
          font-family: 'Helvetica Neue', Arial, sans-serif;
          font-size: 17px;
          // 字体描边实现加粗
          -webkit-text-stroke: 0.6px currentColor;
          // 禁止文本换行
          white-space: nowrap;

          .time-split-char {
            // 时间冒号居中
            display: inline-block;
            transform: translateY(-1.3px);
            font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
          }
        }

        .unread-count {
          top: 57px;
          left: 32px;
          padding: 2px 8px;
          color: $wechat-font-color;
          font-size: 12px;
          background-color: #d5d5d5;
          border-radius: 20px;
          font-weight: 500;
          // 字体描边实现加粗
          // -webkit-text-stroke: 0.3px currentColor;
        }

        .nickname-box {
          top: 55px;

          .nickname {
            padding-inline: 5px;
            font-weight: 500;
            font-size: $wechat-system-font-size;
            color: #181818;
          }
        }

        .content-box {
          height: 685px;
          z-index: 2;
          top: 90.5px;
          left: 0;
          right: 0;
          padding: $chat-box-padding;
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
          overflow: hidden;
        }
      }
    }
  }
}
</style>